﻿using System.Security.Cryptography;
using System.Text;

namespace NaturalNote.Web.utils
{
    public class FileStorage
    {
        private string tempPath = "";
        private string filePath = "";
        public FileStorage(string rootPath)
        {
            tempPath = Path.Combine(rootPath, "_tmp_");
            filePath = Path.Combine(rootPath, "_storage_");
        }
        public string SaveTempFile(Stream st)
        {
            var tmpName = Guid.NewGuid().ToString();
            var tmpFilePath = Path.Combine(tempPath, tmpName);
            if (!Directory.Exists(tempPath))
            {
                Directory.CreateDirectory(tempPath);
            }
            using var fs = File.OpenWrite(tmpFilePath);
            st.CopyTo(fs);
            fs.Close();
            return tmpName;
        }
        public string GetFileHash(string path)
        {
            var tmpFilePath = Path.Combine(tempPath, path);
            using var stream = File.OpenRead(tmpFilePath);
            StringBuilder sb = new StringBuilder();
            using (SHA256 mySHA256 = SHA256.Create())
            {
                byte[] hashValue = mySHA256.ComputeHash(stream);
                foreach (byte b in hashValue)
                {
                    sb.Append(b.ToString("x2"));
                }
            }
            return sb.ToString();
        }

        public string MoveTempFileToStorage(string fileName, string hash)
        {
            var a = hash.Substring(0, 2);
            var b = hash.Substring(2, 4);
            var c = hash.Substring(6, hash.Length - 6);
            var targetPath = Path.Combine(filePath, a, b, c);
            if (File.Exists(targetPath))
            {
                return targetPath;
            }
            var sourcePath = Path.Combine(tempPath, fileName);
            File.Copy(sourcePath, targetPath, false);
            return targetPath;
        }
    }
}
